package com.kasax.plugin.app.visitor.lifecycle

import com.kasax.plugin.app.LogUtils
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes

/**
 * 自定义 ClassVisitor，用于在 Activity 的 onCreate 和 onDestroy 方法中插入日志记录逻辑。
 * 核心功能：
 * 1. 遍历类的方法，识别 onCreate 和 onDestroy 方法。
 * 2. 为这些方法返回自定义的 MethodVisitor，用于插入日志记录逻辑。
 */
class MethodCostClassVisitor extends ClassVisitor {
    ClassWriter writer
    String className
    String TAG = "MethodCostClassVisitor"

    MethodCostClassVisitor(ClassVisitor classVisitor) {
        super(Opcodes.ASM7, classVisitor)
        this.writer = writer
    }

    @Override
    void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces)
        className = name
    }

    @Override
    MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        def methodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions)
        if (methodVisitor == null) {
            LogUtils.d(TAG, "MethodVisitor is null for method: ${name} in class: ${className}")
            return null
        }
        LogUtils.d(TAG, "visitMethod start...")
        LogUtils.d(TAG, "visitMethod method-name: ${name} , className: ${className}")
        //如果是Activity，且是onCreate()返回插入统计方法耗时的Visitor
        if (className.endsWith("Activity") && name == "onCreate") {
            return new CustomCreateMethodVisitor(methodVisitor, className, access, name, descriptor)
        }
        //如果是Activity，且是onDestroy()返回插入测试Log的Visitor
        if (className.endsWith("Activity") && name == "onDestroy") {
            return new CustomDestoryMethodVisitor(methodVisitor, className, access, name, descriptor)
        }
        LogUtils.d(TAG, "visitMethod complete...")
        return methodVisitor
    }
}